"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const fs_1 = __importDefault(require("fs"));
const utils_1 = require("../utils");
const template_1 = require("../utils/template");
const cnpm_api_1 = __importDefault(require("cnpm-api"));
const download_package_tarball_1 = __importDefault(require("download-package-tarball"));
const path_1 = __importDefault(require("path"));
const fs_2 = require("fs");
const child_process_1 = __importDefault(require("child_process"));
const router = express_1.default.Router();
const projectDir = (0, utils_1.getProjectDir)();
const localTemplatesDir = path_1.default.join(projectDir, "/src/templates");
const remoteTemplatesDir = path_1.default.join((0, utils_1.getAppDataDir)(), "/templates");
router.post("/list", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    var _b;
    let localRegisterJson = {
        title: "本地模版",
        value: "local",
        templates: [],
    };
    const registerFilePath = path_1.default.join(localTemplatesDir, "register.json");
    if ((0, fs_2.existsSync)(registerFilePath)) {
        try {
            const json = JSON.parse((0, fs_2.readFileSync)(registerFilePath).toString());
            localRegisterJson = json;
        }
        catch (error) {
            console.log("register.json parse fail \n", error);
        }
    }
    // 1下载或更新本地模版仓库
    const REGISTRY = `http://10.145.11.76:30090`;
    const creator = new cnpm_api_1.default({ registry: REGISTRY });
    const packageList = ["@szzj/page-pdp", "@szzj/page-sjzz"];
    const clientInfo = [];
    if (!fs_1.default.existsSync(remoteTemplatesDir)) {
        fs_1.default.mkdirSync(remoteTemplatesDir);
    }
    for (const packageName of packageList) {
        const data = yield creator.getPackage(packageName);
        const version = (_b = data === null || data === void 0 ? void 0 : data["dist-tags"]) === null || _b === void 0 ? void 0 : _b.latest;
        const packagePath = path_1.default.join(remoteTemplatesDir, packageName);
        let version_local;
        if ((0, fs_2.existsSync)(packagePath)) {
            version_local = (yield (_a = path_1.default.join(packagePath, "package.json"), Promise.resolve().then(() => __importStar(require(_a)))))
                .version;
        }
        if (version !== version_local) {
            yield (0, download_package_tarball_1.default)({
                url: `${REGISTRY}/${packageName}/download/${packageName}-${version}.tgz`,
                dir: remoteTemplatesDir,
            }).catch((err) => {
                throw err;
            });
        }
        clientInfo.push(JSON.parse((0, fs_2.readFileSync)(path_1.default.join(packagePath, "register.json")).toString()));
    }
    const response = (0, utils_1.generoResponse)([
        localRegisterJson,
        ...clientInfo,
    ]);
    res.send(response);
}));
/**
 * 创建本地模版
 */
router.post("/createLocalTemplate", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { dir, title } = req.body;
    const templateDirPath = path_1.default.join(localTemplatesDir, dir);
    const templateFilePath = path_1.default.join(templateDirPath, "index.tsx");
    const registerFilePath = path_1.default.join(localTemplatesDir, "register.json");
    let registerJson = {
        title: "本地模版",
        value: "local",
        templates: [],
    };
    if ((0, fs_2.existsSync)(registerFilePath)) {
        try {
            registerJson = JSON.parse((0, fs_2.readFileSync)(registerFilePath).toString());
            if (registerJson.templates.some((item) => item.title === title)) {
                return res.send((0, utils_1.generoResponse)(null, `模版名称”${title}“重复`));
            }
            const dirList = (0, utils_1.getSubDir)(localTemplatesDir);
            if (dirList.includes(dir)) {
                return res.send((0, utils_1.generoResponse)(null, `模版目录”${dir}“已存在`));
            }
        }
        catch (error) {
            console.error("register.json parse fail \n", error);
            return res.send((0, utils_1.generoResponse)(null, "register.json解析失败"));
        }
    }
    fs_1.default.mkdirSync(templateDirPath, {
        recursive: true,
    });
    fs_1.default.writeFileSync(templateFilePath, "export default () => {return <div>Template</div>}", "utf-8");
    child_process_1.default.exec(`eslint ${templateDirPath} --fix`);
    registerJson.templates.push({
        title,
        value: `src/templates/${dir}`,
    });
    fs_1.default.writeFileSync(registerFilePath, JSON.stringify(registerJson, null, 2), "utf-8");
    res.send((0, utils_1.generoResponse)({
        filePath: templateFilePath,
    }));
}));
router.post("/createPage", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { targetDir, templateDir, type } = req.body;
    let generatedFilePath = "";
    if (type === "local") {
        const absoluteLocalTemplatePathList = path_1.default.join(projectDir, templateDir);
        if (fs_1.default.existsSync(absoluteLocalTemplatePathList)) {
            try {
                const status = (0, template_1.copyDirectorySync)(absoluteLocalTemplatePathList, path_1.default.join(projectDir, targetDir));
                if (!status.success) {
                    return res.send((0, utils_1.generoResponse)(false, status.errMsg));
                }
                generatedFilePath = path_1.default.join(targetDir, "index.tsx");
            }
            catch (e) {
                res.send((0, utils_1.generoResponse)(false, "创建模板失败"));
            }
        }
    }
    else {
        const absoluteRemoteTemplatePathList = path_1.default.join(remoteTemplatesDir, "@szzj", type, templateDir);
        if (fs_1.default.existsSync(absoluteRemoteTemplatePathList)) {
            try {
                const status = (0, template_1.copyDirectorySync)(absoluteRemoteTemplatePathList, path_1.default.join(projectDir, targetDir));
                if (!status.success) {
                    return res.send((0, utils_1.generoResponse)(false, status.errMsg));
                }
                generatedFilePath = path_1.default.join(targetDir, "index.tsx");
            }
            catch (e) {
                res.send((0, utils_1.generoResponse)(false, "创建模板失败"));
            }
        }
        child_process_1.default.execSync(`eslint ${path_1.default.join(projectDir, targetDir)} --fix`);
        console.log("path.join(projectDir, targetDir): ", path_1.default.join(projectDir, targetDir));
    }
    res.send((0, utils_1.generoResponse)({
        filePath: path_1.default.join(projectDir, generatedFilePath),
    }));
}));
exports.default = router;
